/**
 * 排行榜组件
 * 展示用户排名和竞争情况
 */
import React, { useEffect } from 'react';
import {
  Card,
  List,
  Avatar,
  Tag,
  Segmented,
  Space,
  Typography,
  Empty,
  Spin,
  Badge,
} from 'antd';
import {
  TrophyOutlined,
  CrownOutlined,
  FireOutlined,
  StarOutlined,
} from '@ant-design/icons';
import { useStatisticsStore } from '@/stores/statistics.store';
import type { RankingType } from '@/types/statistics';
import './style.css';

const { Text } = Typography;

interface RankingsListProps {
  className?: string;
  limit?: number;
}

export const RankingsList: React.FC<RankingsListProps> = ({ className, limit }) => {
  const {
    rankings,
    selectedRankingType,
    loading,
    loadRankings,
    setRankingType,
  } = useStatisticsStore();

  useEffect(() => {
    loadRankings();
  }, [loadRankings]);

  const handleTypeChange = (value: string | number) => {
    setRankingType(value as RankingType);
  };

  // 获取排名图标和颜色
  const getRankBadge = (rank: number) => {
    if (rank === 1) {
      return { icon: <CrownOutlined />, color: '#FFD700', label: '第一名' };
    }
    if (rank === 2) {
      return { icon: <TrophyOutlined />, color: '#C0C0C0', label: '第二名' };
    }
    if (rank === 3) {
      return { icon: <TrophyOutlined />, color: '#CD7F32', label: '第三名' };
    }
    return { icon: null, color: '#8c8c8c', label: `第${rank}名` };
  };

  // 获取类型标签
  const getTypeLabel = (type: RankingType) => {
    const labels = {
      words: '字数',
      quality: '质量',
      efficiency: '效率',
      templates: '模板',
    };
    return labels[type] || '字数';
  };

  // 获取数值显示
  const getValueDisplay = (value: number, type: RankingType) => {
    switch (type) {
      case 'words':
        return `${value.toLocaleString()} 字`;
      case 'quality':
        return `${value} 分`;
      case 'efficiency':
        return `${value} 分钟/篇`;
      case 'templates':
        return `${value} 次`;
      default:
        return value;
    }
  };

  const renderRankingItem = (item: any, index: number) => {
    const rankBadge = getRankBadge(item.rank);
    const isTopThree = item.rank <= 3;
    const isCurrentUser = rankings?.myRank === item.rank;

    return (
      <List.Item
        className={`ranking-item ${isTopThree ? 'top-three' : ''} ${isCurrentUser ? 'current-user' : ''}`}
      >
        <div className="ranking-content">
          {/* 排名标识 */}
          <div className="ranking-badge">
            {isTopThree ? (
              <Badge
                count={rankBadge.icon}
                style={{
                  backgroundColor: rankBadge.color,
                  color: '#fff',
                  fontSize: 16,
                  width: 36,
                  height: 36,
                  lineHeight: '36px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                }}
              />
            ) : (
              <div className="ranking-number">{item.rank}</div>
            )}
          </div>

          {/* 用户信息 */}
          <div className="ranking-user">
            <Avatar
              src={item.avatar}
              size={isTopThree ? 48 : 40}
              style={{
                border: isTopThree ? `2px solid ${rankBadge.color}` : 'none',
              }}
            >
              {item.username[0]}
            </Avatar>
            <div className="user-info">
              <Space>
                <Text strong className="username">
                  {item.username}
                </Text>
                {isCurrentUser && (
                  <Tag color="blue" icon={<StarOutlined />}>
                    我
                  </Tag>
                )}
                {isTopThree && (
                  <Tag color={rankBadge.color} style={{ border: 'none' }}>
                    {rankBadge.label}
                  </Tag>
                )}
              </Space>
            </div>
          </div>

          {/* 数值显示 */}
          <div className="ranking-value">
            <Text strong style={{ fontSize: isTopThree ? 18 : 16 }}>
              {getValueDisplay(item.value, selectedRankingType)}
            </Text>
          </div>
        </div>
      </List.Item>
    );
  };

  return (
    <div className={`rankings-list ${className || ''}`}>
      <Card
        title={
          <Space>
            <FireOutlined />
            <span>创作排行榜</span>
          </Space>
        }
        extra={
          <Segmented
            value={selectedRankingType}
            onChange={handleTypeChange}
            options={[
              { label: '字数', value: 'words', icon: <TrophyOutlined /> },
              { label: '质量', value: 'quality', icon: <StarOutlined /> },
              { label: '效率', value: 'efficiency', icon: <FireOutlined /> },
              { label: '模板', value: 'templates', icon: <CrownOutlined /> },
            ]}
            size="small"
          />
        }
      >
        <Spin spinning={loading}>
          {!rankings || rankings.rankings.length === 0 ? (
            <Empty description="暂无排行数据" style={{ padding: '40px 0' }} />
          ) : (
            <>
              {/* 我的排名 */}
              {rankings.myRank && rankings.myRank > 0 && (
                <div className="my-ranking">
                  <Space>
                    <Text type="secondary">我的排名:</Text>
                    <Text strong style={{ fontSize: 16 }}>
                      第 {rankings.myRank} 名
                    </Text>
                    <Text type="secondary">/ 共 {rankings.total} 人</Text>
                  </Space>
                </div>
              )}

              {/* 排行榜列表 */}
              <List
                dataSource={limit ? rankings.rankings.slice(0, limit) : rankings.rankings}
                renderItem={renderRankingItem}
                className="rankings-list-content"
              />
            </>
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default RankingsList;
